//
//  PYEditViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/8.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit

enum PYEditType {
    case add
    case edit
}

class PYEditViewController: SYBaseViewController {
    
    var type: PYEditType!
    
    var choiceView: PYPublishChoiceView!
    var imageChoice = PYImageChoiecView()
    var choiceImages:[UIImage] = []
    var uploadImgIds = Array<String>()
    var contentStr: String = ""
    var videoUrl: URL?
    let cancel: UIButton = {
        let v: UIButton  = UIButton()
        v.setTitle("取消", for: .normal)
        v.setTitleColor(UIColor(hex: 0x333333), for: .normal)
        v.titleLabel?.font = 14.autoFontSize()
        return v
    }()
    
    let publish: UIButton = {
        let v: UIButton  = UIButton()
        v.setTitle("发表", for: .normal)
        v.setTitleColor(UIColor.white, for: .normal)
        v.titleLabel?.font = 15.autoFontSize()
        v.backgroundColor = UIColor(hex: 0x367FF6)
        v.layer.cornerRadius = 5
        return v
    }()
    
    fileprivate var titleLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = UIFont.systemFont(ofSize: 17)
        v.textColor = UIColor(hex: 0x333333)
        v.text = "编辑"
        return v
    }()
    
    var textView: UITextView = {
        let v: UITextView = UITextView()
        v.font = 17.autoFontSize()
        
        return v
    }()
    
    var moren: UILabel = {
        let v: UILabel = UILabel()
        v.font = UIFont.systemFont(ofSize: 16)
        v.textColor = UIColor(hex: 0x999999)
        v.text = "分享农友圈子..."
        return v
    }()
    
    let tap: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapPicture(tap:)))
    
    
    public var lineView: UIView = {
        let v: UIView = UIView()
        v.backgroundColor = UIColor(hex: 0xE6E6E6)
        return v
    }()
    
    init(type: PYEditType = .add, model: PYMyDetailModel? = nil) {
        super.init(nibName: nil, bundle: nil)
        self.type = type
        
        if type == .edit {
            
            self.contentStr  = model?.content ?? ""
            
            if let u = model?.resourceList {

                if let p = u.first?.videoImgUrl {

                    SYDownloadImage().downloadImages(urls: [p], noHud: false) { (images) in
                        self.choiceImages.append(contentsOf: images)
                        self.imageChoice.lastImages = self.choiceImages

                        if let vp = u.first?.fileFullPath {
                            SYDownloadVideo().downloadVideo(url: IP + vp) { (localURL) in
                                self.videoUrl = localURL
                            }
                        }
                    }
                } else {
                        SYDownloadImage().downloadImages(urls: u.map { ($0.fileFullPath ?? "") }, noHud: false) { (images) in
                        self.choiceImages.append(contentsOf: images)
                        self.imageChoice.lastImages = self.choiceImages
                    }
                    
                }
            }
            if !self.contentStr.isEmpty {
                self.textView.text = self.contentStr
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        creatNavBts()
        setupChoiceImageView()
        setupChoiceView()
        moren.addGestureRecognizer(tap)
        
    }
    
    func requestRelease(content:String, imgUrl: String, complete:@escaping (Bool)->()) {
        requestVM.baseRequest(disposeBag: dispose, type: .release(dic: ["content": content, "imgUrl": imgUrl]), modelClass: SGBaseModel<SGPagerTestModel>.self) {[weak self] (res) in
            if let `self` = self {
                complete(true)
            }
            
        } Error: {
            complete(false)
        }
        
    }
    
    func requestUploadImages(imgs:[UIImage], complete:@escaping ([PYUploadImageModel]?)->()) {
        requestVM.baseRequest(disposeBag: dispose, type: .uploadImages(imgs: imgs), modelClass: SGBaseNoPageListModel<PYUploadImageModel>.self) {[weak self] (res) in
            if let `self` = self {
                complete(res.data)
            }
            
        } Error: {
            
        }
    }
    
    func requestUploadVideo(url:URL, complete:@escaping ([PYUploadImageModel]?)->()) {
        requestVM.baseRequest(disposeBag: dispose, type: .uploadVideo(url: url), modelClass: SGBaseNoPageListModel<PYUploadImageModel>.self) {[weak self] (res) in
            if let `self` = self {
                complete(res.data)
            }
            
        } Error: {
            
        }
    }
    
    
    func creatNavBts() {
        
        cancel.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        publish.addTarget(self, action: #selector(publishAction), for: .touchUpInside)
        //当文本框内容改变时，将内容输出到控制台上
        textView.rx.text.orEmpty.asObservable()
            .subscribe(onNext: {
                print("您输入的是：\($0)")
                if $0 == "" {
                    self.moren.isHidden = false
                } else {
                    self.moren.isHidden = true
                }
                
            })
            .disposed(by: dispose)
        
        //开始编辑响应
        textView.rx.didBeginEditing
            .subscribe(onNext: {
                print("开始编辑")
                self.choiceView.isHidden = true
            })
            .disposed(by: dispose)
        //结束编辑响应
        textView.rx.didEndEditing
            .subscribe(onNext: {
                print("结束编辑")
                self.contentStr = self.textView.text
            })
            .disposed(by: dispose)
        
        view.addSubview(cancel)
        view.addSubview(publish)
        view.addSubview(titleLb)
        view.addSubview(textView)
        view.addSubview(lineView)
        textView.addSubview(moren)
        cancel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15.0)
            make.top.equalToSuperview().offset(7+STATUSBAR_HEIGHT)
            make.width.equalTo(60.autoWidth())
            make.height.equalTo(30.autoWidth())
        }
        
        publish.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15.0)
            make.top.equalToSuperview().offset(7+STATUSBAR_HEIGHT)
            make.width.equalTo(60.autoWidth())
            make.height.equalTo(30.autoWidth())
        }
        titleLb.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(cancel)
            make.height.equalTo(30.autoWidth())
            
        }
        textView.snp.makeConstraints { (make) in
            make.top.equalTo(lineView.snp.bottom).offset(8.0)
            make.left.equalToSuperview().offset(15.0)
            make.right.equalToSuperview().offset(-15.0)
            make.height.equalTo(200.autoWidth())
            
        }
        moren.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(8.0)
            make.left.equalToSuperview().offset(5.0)
            make.right.equalToSuperview().offset(-5.0)
            make.height.equalTo(20.autoWidth())
        }
        lineView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(44.0+STATUSBAR_HEIGHT)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(0.5.autoWidth())
            
        }
        
    }
    
    fileprivate func setupChoiceView() {
        
        self.choiceView = PYPublishChoiceView(frame: CGRect(x: 0, y: SCREEN_HEIGHT - 248-BOTTOM_SAFE_HEIGHT, width: SCREEN_WIDTH, height: 248))
        self.choiceView.currentVC = self
        self.choiceView.choiceClosure = {[weak self] (imgs, url) in
            if let `self` = self {
                
                self.choiceImages = imgs
                self.videoUrl = url
            }
            
        }
        view.addSubview(choiceView)
    }
    
    func setupChoiceImageView() {
        
        imageChoice.currentVC = self
        view.addSubview(imageChoice)
        imageChoice.snp.makeConstraints { (make) in
            make.top.equalTo(textView.snp.bottom).offset(8.0)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(230.autoWidth())
            
        }
    }
    
    @objc func tapPicture(tap: UITapGestureRecognizer) {
        moren.isHidden = true
    }
    
    @objc func cancelAction() {
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func publishAction() {
        
        if self.contentStr.isEmpty {
            self.sy_toast( "请输入文字信息")
            return
        }
        if let u = self.videoUrl {
            
            self.requestUploadVideo(url: u) { (models) in
                if let m = models {
                    m.forEach({ (value) in
                        self.uploadImgIds.append(value.id ?? "")
                    })
                    self.requestRelease(content: self.contentStr, imgUrl: self.uploadImgIds.joined(separator: ",")) { (success) in
                        if success {
                            self.uploadImgIds.removeAll()
                            self.contentStr = ""
                            self.videoUrl = nil
                            self.sy_toast(Constant_Toast.fabiaoSuccess) { (_) in

                                self.popVC()
                            }
                        }
                    }
                }
            }
            
        } else {
            
            
            if self.choiceImages.count == 0 {
                self.sy_toast( "请选择图片或视频")
                return
            }
            
            self.requestUploadImages(imgs: choiceImages) { (models) in
                if let m = models {
                    m.forEach({ (value) in
                        self.uploadImgIds.append(value.id ?? "")
                    })
                    self.requestRelease(content: self.contentStr, imgUrl: self.uploadImgIds.joined(separator: ",")) { (success) in
                        if success {
                            self.uploadImgIds.removeAll()
                            self.contentStr = ""
                            self.sy_toast(Constant_Toast.fabiaoSuccess) { (_) in
                                self.popVC()
                            }
                        }
                    }
                }
            }
            
        }
        
    }
    func getRequestUrl(api: String) -> String {
        return IP + VERSION + api
    }
    
    func getHeader() -> [String: String] {
        let token: String = UserDefaults.standard.value(forKey: "token") as? String ?? ""
        return ["token": token, "Authorization": token]
    }
}

/// 选择控件model基础类
class PYChoiceModel:Codable {
    
    var title: String?
}
